package com.gzw.dms.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.Receiver.NetReceiver;
import com.gzw.dms.adapter.NewDpAdapter;
import com.gzw.dms.base.BaseFragment;
import com.gzw.dms.bean.ShippingOrderInfo;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2016/3/10.
 */
public class Ddfp1Frager  extends BaseFragment {
    private PullToRefreshListView mPullToRefreshListView;
    private ListView lv_order;
    private Context mContext;
    private ProgressDialog mProgressDialog;
    private TextView tv_seleteAll;
    private int refresh = 0;
    private int loadmore = 0;
    private List<ShippingOrderInfo> shippingOrderInfo;
    private LinkedList<ShippingOrderInfo> allshippingOrderInfo;
    private boolean isCheck = false;
    private String rownum = "1";
    private String rows = "10";
    private String shiping_order_goid = "";
    private String custom_name = "";
    private String receipt_name = "";
    private String shippingOderId = "";
    private String order_num1,shiping_order_goid1,custom_name1,receipt_name1;
    private List<String> ls_map;
    private TextView tv_select;
    private DrawerLayout drawer;
    private NavigationView navigationView;
    private TextView tv_name, tv_accunt;
    private NewDpAdapter newDpAdapter;

    private LinkedList<String> mItemList;
    private ArrayAdapter<String> adapter;


    NetReceiver mReceiver = new NetReceiver();
    IntentFilter mFilter = new IntentFilter();
    private LocalBroadcastManager broadcastManager;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        broadcastManager.registerReceiver(mReceiver, mFilter);
        return super.onCreateView(inflater, container, savedInstanceState);
    }
    @Override
    protected View setContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_ddfg1, null);


    }

    @Override
    protected void initViews() {
        initData1();
        mContext = getContext();
        newDpAdapter = new NewDpAdapter(mContext, R.layout.item_order1, allshippingOrderInfo);
        adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, mItemList);

        mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.lv_order);
        lv_order = mPullToRefreshListView.getRefreshableView();
        lv_order.setAdapter(adapter);
        mPullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);

        tv_seleteAll = (TextView) findViewById(R.id.ic_head1).findViewById(R.id.tv_selectAll);
        tv_select = (TextView) findViewById(R.id.tv_select);
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        View headerView = navigationView.getHeaderView(0);
        tv_name = (TextView) headerView.findViewById(R.id.nav_userName);
        tv_accunt = (TextView) headerView.findViewById(R.id.nav_accunt);

    }


    private void initData1(){

        mItemList = new LinkedList<String>();
        mItemList.addAll(Arrays.asList(data));
        allshippingOrderInfo=new LinkedList<ShippingOrderInfo>();
//        ShippingOrderInfo shippingOrderInfo = new ShippingOrderInfo();
//        for (int i=0;i<10;i++){
//            allshippingOrderInfo.add(shippingOrderInfo);
//        }

    }

    private String[] data  = new String[]{"","","","","","",

            "","","","","",""};


    @Override
    protected void initEvents() {
        tv_seleteAll.setOnClickListener(new myOnClick());
        tv_select.setOnClickListener(new myOnClick());
        lv_order.setOnItemClickListener(new mOnItemClick());


        //设置上拉下拉事件
        mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {

                if (refreshView.isHeaderShown()) {//下拉刷新 业务代码
                    refresh = 1;
                    rownum = "1";
                    ShowOrderTask showOrderTask = new ShowOrderTask();
                    showOrderTask.execute(rownum, rows, shippingOderId, shiping_order_goid, custom_name, receipt_name);

                }
                if (refreshView.isFooterShown()) {
                    //上拉加载更多 业务代码
                    refresh = 2;
                    if(loadmore == 0) {
                        rownum = String.valueOf(newDpAdapter.getCount() + 1);
                        ShowOrderTask showOrderTask = new ShowOrderTask();
                        showOrderTask.execute(rownum, rows, shippingOderId, shiping_order_goid, custom_name, receipt_name);
                    }else if(loadmore == 1){
                        rownum = String.valueOf(newDpAdapter.getCount() + 1);
                        ShowOrderTask showOrderTask = new ShowOrderTask();
                        showOrderTask.execute(rownum, rows, order_num1,shiping_order_goid1,custom_name1,receipt_name1);
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        mContext = getContext();
        setHasOptionsMenu(true);
        ls_map = new ArrayList<>();
//        allshippingOrderInfo=new ArrayList<ShippingOrderInfo>();

        ShowOrderTask showOrderTask = new ShowOrderTask();
        showOrderTask.execute(rownum, rows,shippingOderId,shiping_order_goid,custom_name,receipt_name);

    }


    class mOnItemClick implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ShippingOrderInfo shippingOrder = (ShippingOrderInfo) parent.getItemAtPosition(position);
                Intent mIntetn = new Intent();
                Bundle bundle = new Bundle();
                mIntetn.setClass(mContext, ShippingOrderDetailActivity.class);
                bundle.putSerializable("shippingOrder", shippingOrder);
                mIntetn.putExtras(bundle);
                mIntetn.putExtra("fpstste", "5");
                startActivityForResult(mIntetn, 1);

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        rownum = "1";
        if (resultCode == 1) {
            refresh = 0;
            ShowOrderTask showOrderTask = new ShowOrderTask();
            showOrderTask.execute(rownum, rows,shippingOderId,shiping_order_goid,custom_name,receipt_name);
        }else if(resultCode == 2){
            refresh = 0;
            loadmore = 1;
            order_num1 = (String) data.getExtras().get("order_num");
            shiping_order_goid1 = (String) data.getExtras().get("shiping_order_goid");
            custom_name1
                    = (String) data.getExtras().get("custom_name");
            receipt_name1
                    = (String) data.getExtras().get("receipt_name");

            ShowOrderTask showOrderTask = new ShowOrderTask();
            showOrderTask.execute(rownum, rows, order_num1,shiping_order_goid1,custom_name1,receipt_name1);
        }

    }

    /**
     * Created by Wangzhiqiang on 2015-10-11
     * 单击事件
     */
    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.tv_selectAll:
                    if (allshippingOrderInfo != null) {
                        if (isCheck == false) {
                            // 遍历list的长度，将MyAdapter中的map值全部设为true
                            for (int i = 0; i < allshippingOrderInfo.size(); i++) {
                                newDpAdapter.getIsSelected().put(i, true);
                            }
                            dataChanged();
                            //改变状态
                            isCheck = true;
                        } else {
                            // 遍历list的长度，将已选的按钮设为未选
                            for (int i = 0; i < allshippingOrderInfo.size(); i++) {
                                if (NewDpAdapter.getIsSelected().get(i)) {
                                    newDpAdapter.getIsSelected().put(i, false);
                                }
                            }
                            dataChanged();
                            isCheck = false;
                        }
                    }
                    break;
                case R.id.tv_select:
                    Intent mIntetn = new Intent();
                    mIntetn.setClass(mContext, TJSelectActivity.class);
                    startActivityForResult(mIntetn, 1);
                    break;
            }

        }
    }


    // 刷新listview和TextView的显示
    private void dataChanged() {
        // 通知listView刷新
        newDpAdapter.notifyDataSetChanged();
    }


    public class ShowOrderTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            if (refresh == 0) {
                mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
                mProgressDialog.setCancelable(true);
            }
        }

        protected String doInBackground(String... params) {
            Map<String, String> map = new HashMap<>();
            map.put("suppliers_id", MyApplication.getUserInfo().getSuppliers_id());
            map.put("rownum", params[0]);
            map.put("rows", params[1]);
            map.put("shippingOderId",params[2]);
            map.put("shiping_order_goid",params[3]);
            map.put("custom_name",params[4]);
            map.put("receipt_name", params[5]);

            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("getShipOrder"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            if (refresh == 0) {
                mProgressDialog.dismiss();
            }
            else if(refresh == 1){
                mPullToRefreshListView.onRefreshComplete();
            }else if(refresh == 2){
                mPullToRefreshListView.onRefreshComplete();

            }

            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {
                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    shippingOrderInfo = JsonUtil.getPersons(successMsg, new TypeToken<List<ShippingOrderInfo>>() {
                    }.getType());

                    if(refresh==2 && shippingOrderInfo.size()==0){
                        T.showShort(mContext,"已无更多数据!");
                        return;
                    }

                    if(refresh == 0){
                        allshippingOrderInfo.clear();
                        allshippingOrderInfo.addAll(shippingOrderInfo);
                    }
                   else if (refresh == 1){
                        allshippingOrderInfo.clear();
                        allshippingOrderInfo.addAll(shippingOrderInfo);

                        // 遍历list的长度，将已选的按钮设为未选
                        for (int i = 0; i < allshippingOrderInfo.size(); i++) {
                            if (NewDpAdapter.getIsSelected().get(i)) {
                                newDpAdapter.getIsSelected().put(i, false);
                            }
                        }
                        isCheck = false;

                    }else  if (refresh == 2){
                        allshippingOrderInfo.addAll(shippingOrderInfo);

                        // 遍历list的长度，将已选的按钮设为未选
                        for (int i = 0; i < allshippingOrderInfo.size(); i++) {
                            if (NewDpAdapter.getIsSelected().get(i)) {
                                newDpAdapter.getIsSelected().put(i, false);
                            }
                        }
                        isCheck = false;
                    }

                    if (newDpAdapter == null) {
                        newDpAdapter = new NewDpAdapter(mContext, R.layout.item_order1, allshippingOrderInfo);

                    }else {
                    dataChanged();
                    }
                }
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Inflate the menu_home; this adds items to the action bar if it is present.
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_fp, menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_fp:
                ls_map.clear();
                for (int i = 0; i < allshippingOrderInfo.size(); i++) {
                    if (newDpAdapter.getIsSelected().get(i)) {
                        ls_map.add(allshippingOrderInfo.get(i).getShiping_order_id());
                    }
                }
                if (ls_map.size() == 0) {
                    T.showShort(mContext, "请先选择要分配的运单!");
                } else {
                    Intent mIntetn = new Intent();
                    mIntetn.setClass(mContext, SelectDriverActivity.class);
                    mIntetn.putStringArrayListExtra("ls_map", (ArrayList<String>)ls_map);
                    startActivityForResult(mIntetn, 1);
                }
                break;
        }
        return super.onOptionsItemSelected(item);

    }


    @Override
    public void onDestroy() {
        broadcastManager.unregisterReceiver(mReceiver);
        super.onDestroy();
    }

}

